<template>
    <div class="chat-app h-screen flex flex-col pb-[1.3rem]">
        <header class="app-header sticky top-0 z-10 bg-gray-800 h-[1.5rem] text-white flex items-center justify-center">
            <h1 class="text-[0.7rem] font-bold">AI Chat Assistant</h1>
        </header>

        <div class="message-list flex-1 overflow-y-auto p-1 overflow-auto" ref="messageContainer">
            <div class="message-item flex mt-1" v-for="(item, index) in messages" :key="index"
                :class="[item.role === 'bot' ? 'justify-start' : 'justify-end']">
                <div class="rounded p-1" :class="[
                    isImagePresent(item.content)
                        ? 'bg-black bg-opacity-70'
                        : 'bg-gray-100',
                ]">
                    <p class="leading-normal text-[0.4rem]" :class="[
                        isImagePresent(item.content) ? 'text-white' : 'text-black',
                    ]">
                        {{ item.content }}
                    </p>
                    <img v-if="isImagePresent(item.content)" :src="item.content" alt="Message Image"
                        class="mt-1 rounded" />
                </div>
            </div>
        </div>

        <footer class="app-footer bg-gray-100 border-t border-gray-200 rounded-sm px-1" ref="footer">
            <div class="app-footer-content flex items-center justify-between py-1 space-x-1">
                <input type="text" v-model="newMessage" @keyup.enter="sendMessage"
                    placeholder="Type your message here..."
                    class="w-full p-[0.2rem] text-[0.4rem] text-gray-700 bg-white border border-gray-300 rounded-sm" />
                <button @click="sendMessage"
                    class="ml-2 p-[0.2rem] text-[0.4rem] text-white bg-blue-500 hover:bg-blue-600 rounded-sm">
                    Send
                </button>
            </div>
        </footer>
    </div>
</template>

<script setup>
import { ref, watch, onMounted, nextTick } from "vue";
import { useAiMessageStore } from "@/stores/aiMessageStore.ts";

const newMessage = ref("");
const messageContainer = ref(null);
const footer = ref(null);

const { messages, addMessage } = useAiMessageStore();

// 检查消息是否包含图片链接
function isImagePresent(content) {
    return content.startsWith("http") && /\.(jpe?g|png|gif)$/i.test(content);
}

// 发送新消息
function sendMessage() {
    data.query = newMessage.value;
    addMessage({ role: "user", content: newMessage.value });
    newMessage.value = ""; // 清空输入框
    scrollToBottom();

    // 发送 POST 请求
    fetch(url, {
        method: "POST", // 或者 'GET'
        headers: headers,
        body: JSON.stringify(data), // 转换数据为 JSON 格式
        cache: "no-cache", //
        credentials: "same-origin", //
        redirect: "follow", //
        referrerPolicy: "no-referrer", //
    })
        .then((response) => response.json()) // 解析响应为 JSON 格式
        .then((data) => {
            console.log("Success:", data);
            addMessage({ role: "bot", content: data.messages[0].content });
            scrollToBottom();
        })
        .catch((error) => {
            console.error("Error:", error);
        });
}

// 监听消息变化，自动滚动到底部
watch(
    () => messages.value,
    () => {
        nextTick(() => {
            if (messageContainer.value && footer.value) {
                scrollToBottom();
            }
        });
    },
    { deep: true }
);

// 组件挂载后，滚动到容器底部
onMounted(() => {
    if (messageContainer.value && footer.value) {
        scrollToBottom();
    }
});

// 滚动到底部的函数
function scrollToBottom() {
    if (messageContainer.value && footer.value) {
        const footerHeight = footer.value.clientHeight;
        messageContainer.value.scrollTop = Math.max(
            0,
            messageContainer.value.scrollHeight - footerHeight
        );
    }
}

// 向coze对应的bot发送接口请求
const url = "https://api.coze.cn/open_api/v2/chat";
const headers = {
    Authorization:
        "Bearer pat_LGCNTRLVb07bMncNfhmDnuXfWeJcrQJfbDRkQRbju1kc9RmLW0vIAoM1O3u55OBw",
    "Content-Type": "application/json",
    Connection: "keep-alive",
    Accept: "*/*",
};
const data = {
    bot_id: "7396161788096004130",
    conversation_id: "11",
    user: "user_1",

    stream: false,
};
</script>
